//
//  JuvidHTTPClient.m
//  YunServer
//
//  Created by Juvid on 14/10/29.
//  Copyright (c) 2014年 Juvid. All rights reserved.
//

#import "JuvidHTTPClient.h"
#import "KeychainItemWrapper.h"
#import "Common.h"
@implementation JuvidHTTPClient


+ (instancetype)sharedClient {
    static JuvidHTTPClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[JuvidHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
        [_sharedClient SetStatrHttp];
    });
    return _sharedClient;
}
+ (instancetype)sharedNoClient {
    static JuvidHTTPClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[JuvidHTTPClient alloc] init];
        [_sharedClient SetStatrHttp];
    });
    return _sharedClient;
}
-(id)init{
    self=[super init];
    if (self) {
        netStatus=[JuvidNetStatus sharedNet];
    }
    return self;
}

- (void)postPath:(NSString *)path
      parameters:(NSDictionary *)parameters
           block:(void(^)(id json))processResult
       failblock:(void(^)(NSError *error))failresult{
    [self SetHeadHttp];
    [self POST:path parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"POST  \n%@\n%@   \n%@",path,operation.request.allHTTPHeaderFields,operation.response.allHeaderFields);
        if (operation.response.allHeaderFields[@"token"]) {
        }
        processResult(responseObject);
        //        request.requestCookies
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failresult(error);
    }];
    
}
- (void)getPath:(NSString *)path
          block:(void(^)(id json))processResult
      failblock:(void(^)(NSError *error))failresult
{
    [self getPath:path parameters:nil block:processResult failblock:failresult];
}
- (void)getPath:(NSString *)path
     parameters:(NSDictionary *)parameters
          block:(void(^)(id json))processResult
      failblock:(void(^)(NSError *error))failresult
{
    [self SetHeadHttp];
    path=[path stringByAddingPercentEscapesUsingEncoding: CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8)];
    
    URLCache *urlCache=[[URLCache alloc]initWithPath:path Parameter:parameters];
    //无网络刷新时间没过期都使用缓存
    /* if ([urlCache GetCacheValue]||(!netStatus.connectionRequired&&[urlCache isCached])) {
     processResult([urlCache GetCached]);
     return;
     }*/
    [self GET:path parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [urlCache saveCacheInfo:responseObject];
        //        po operation.request.allHTTPHeaderFields
        NSLog(@"GET  \n%@  \n%@   \n%@",path,operation.request.allHTTPHeaderFields,operation.response.allHeaderFields);
        processResult(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if ([urlCache isCached]) {
            processResult([urlCache GetCached]);
        }
        else{
            failresult(error);
        }
    }];
}
-(void)SetHeadHttp{
    //    "Set-Cookie" = "JSESSIONID=EC8EDB65A3B83526C703370175251FB4; Path=/portal/; HttpOnly";
    //    "Content-Length" = 847;
    //    "Content-Type" = "application/json;charset=UTF-8";
    //    Date = "Sat, 29 Nov 2014 15:53:59 GMT";
    //    Server = "Apache-Coyote/1.1";
    //    "Set-Cookie" = "JSESSIONID=EF345F714144A7CEA1D5A35BA554AACC; Path=/portal/; HttpOnly";
    
    //    Accept-Language
    [self.requestSerializer setValue:[Common GetDeviceID] forHTTPHeaderField:@"HD_UUID"];
    [self.requestSerializer setValue:[Common GetUserToken] forHTTPHeaderField:@"HD_TOKEN"];
    [self.requestSerializer setValue:[Common GetLocationLL] forHTTPHeaderField:@"HD_LOCATION"];
    [self.requestSerializer setValue:[Common GetRegionId] forHTTPHeaderField:@"HD_REGION"];
    
}
-(void)SetStatrHttp{
    [self.requestSerializer setValue:[NSString stringWithFormat:@"%f*%f",WINDOWH,WINDOWW] forHTTPHeaderField:@"HD_RESOLUTION"];
    [self.requestSerializer setValue:@"客户端渠道ID" forHTTPHeaderField:@"HD_CHANNEL"];
    [self.requestSerializer setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"HD_SYSTEM"];
    [self.requestSerializer setValue:[[UIDevice currentDevice] model] forHTTPHeaderField:@"HD_CLIENT_TYPE"];
    [self.requestSerializer setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey]forHTTPHeaderField:@"HD_VERSION"];
}


//AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//NSDictionary *parameters = @{@"foo": @"bar"};
//NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
//[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
//} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//    NSLog(@"Success: %@", responseObject);
//} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//    NSLog(@"Error: %@", error);
//}];
@end
